package com.xsd.awen.utils;

import com.xsd.awen.config.ServiceException;
import org.apache.commons.beanutils.PropertyUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Maps {

    public static int page(Map<String,Object> param){
        return Integer.valueOf(param.get("page").toString());
    }

    public static int limit(Map<String,Object> param){
        return Integer.valueOf(param.get("limit").toString());
    }

    public static String getString(Map<String,Object> param,String key){
        Object obj = param.get(key);
        if( obj == null ){
            return null;
        }else {
            return obj.toString();
        }
    }

    public static int getInt(Map<String,Object> param,String key){
        Object obj = param.get(key);
        if( obj == null ){
            return -1;
        }else {
            return Integer.valueOf(obj.toString());
        }
    }

    private Map<String,Object> map = Maps.newHashmap();

    public static <K,V> HashMap<K,V> newHashmap() {
        return new HashMap<>();
    }

    public static Maps newMap(){
        return new Maps();
    }

    public static Maps newMap(Map<String,String> map){
        Maps maps = new Maps();
        for( String key : map.keySet() ){
            maps.put(key,map.get(key));
        }
        return maps;
    }

    public Maps put(String key ,Object value){
        map.put(key,value);
        return this;
    }

    public Map<String,Object> value(){
        return map;
    }

    public Object get(String key){
        return map.get(key);
    }

    public List<Object> toList(String keys){
        return toList(keys,"");
    }

    public List<Object> toList(String keys,String prefix){
        List<Object> list = Lists.newArrayList();
        String[] keyArr = keys.split(",");
        for( int i=0  ; i<keyArr.length ; i++ ){
            String key = prefix+Strings.toHump(keyArr[i]);
            list.add(map.get(key));
        }
        return list;
    }

    // map utils
    public static <T> T toEntity(Map<String,Object> map,Class<T> entityClass){
        T t;
        try {
            t = entityClass.newInstance();

            List<String> properties = ClassUtils.getProperties(entityClass);
            for( String property : properties ){
                PropertyUtils.setProperty(t,property, map.get(property));
            }
            return t;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

}
